<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    /*public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }*/

    public function render($request, Exception $e)
    {
        if ($request->header('halo-debug')) {
            return parent::render($request, $e);
        }

        $rendered = parent::render($request, $e);
        $code     = $rendered->getStatusCode();

        $msg  = $e->getMessage();
        $info = [
            401 => 'Unauthorized.',
            404 => '数据不存在',
            405 => 'Method Not Allowed',
            500 => '哎呀服务器开小差啦',
        ];

        if (env('APP_ENV') == 'dev' && $code == 500) {
            $info[500] = $msg;
        }

        if (isset($info[$code])) {
            $msg = $info[$code];
        }

        $header = method_exists($e, 'getHeaders') ? $e->getHeaders() : [];

        if ($code == 500 && env('APP_ENV') != 'dev') {
            $body = '#### 异常描述（' . $request->header('halo-app') . '）' . "\n\r";
            $body .= '> ' . $e->getMessage() . "\n\r";

            $body .= '#### 路由信息' . "\n\r";
            $body .= '> ' . $request->url() . "\n\r";

            $body .= '#### 参数信息' . "\n\r";
            $body .= '> ' . var_export($request->all(), 1) . "\n\r";

            $body .= '#### HEADER信息' . "\n\r";
            $body .= '> ' . var_export($request->header(), 1) . "\n\r";

            $body .= '#### Trace信息' . "\n\r";
            $body .='> ' . $e->getTraceAsString();

            // 写入文件
            // $filename = time() . '.log';
            // write_temp_log($filename, $e->getTraceAsString());
            //
            // $body .= '[详细日志点击查看](' . get_host() . 'static/logs_temp/' . date('Ymd') . '/' . $filename . ') ';

            //dingding_robot($body);
        }

        return response()->json([
            'iRet' => $code == 401 ? -1 : 0,
            'info' => $msg,
            'data' => isset($header['ret_data']) ? $header['ret_data'] : (object)[],
        ], $code);
    }
}
